/**
 * 渲染系统 - 绘制所有可见实体
 */
import { System, World } from '../ecs';
import { Transform, Renderer } from '../components';

export class RenderSystem implements System {
  priority = 100; // 最后执行

  update(deltaTime: number, world: World): void {
    const { ctx, width, height } = world.resources;

    // 清空画布
    ctx.fillStyle = '#020612';
    ctx.fillRect(0, 0, width, height);

    // 绘制星空背景
    this.drawStarField(ctx, width, height);

    // 绘制所有实体
    for (const entity of world.entities) {
      const transform = entity.getComponent<Transform>('transform');
      const renderer = entity.getComponent<Renderer>('renderer');
      
      if (!transform || !renderer) continue;

      ctx.save();
      ctx.translate(transform.x, transform.y);
      ctx.rotate(transform.rotation);

      this.drawShape(ctx, renderer);

      ctx.restore();
    }
  }

  private drawShape(ctx: CanvasRenderingContext2D, renderer: Renderer): void {
    ctx.fillStyle = renderer.color;
    ctx.strokeStyle = renderer.color;
    ctx.lineWidth = 2;

    switch (renderer.shape) {
      case 'circle':
        ctx.beginPath();
        ctx.arc(0, 0, renderer.radius, 0, Math.PI * 2);
        ctx.fill();
        break;

      case 'triangle':
        ctx.beginPath();
        ctx.moveTo(0, -renderer.radius);
        ctx.lineTo(-renderer.radius * 0.8, renderer.radius * 0.6);
        ctx.lineTo(renderer.radius * 0.8, renderer.radius * 0.6);
        ctx.closePath();
        ctx.fill();
        ctx.stroke();
        break;

      case 'square':
        ctx.fillRect(-renderer.radius, -renderer.radius, 
                    renderer.radius * 2, renderer.radius * 2);
        break;
    }
  }

  private drawStarField(ctx: CanvasRenderingContext2D, width: number, height: number): void {
    ctx.fillStyle = '#ffffff';
    // 简单的星空效果
    for (let i = 0; i < 100; i++) {
      const x = Math.random() * width;
      const y = Math.random() * height;
      const size = Math.random() * 2;
      ctx.fillRect(x, y, size, size);
    }
  }
}